package edu.csula.cs575;







import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;

public class MainPage extends Activity {
	ListView list;
	String[] mString = {"Hospital", "Pharmacy","Shelter","Stores"};
	ImageButton sos;
	ImageButton wifiButton;
	ImageButton mapButton;
	ToggleButton hotSpot;
	Button yesBtn;
	Button noBtn;
	int level = 50;
	TextView batteyLevel;
	private int GET_CODE;
	WifiConfiguration netConfig;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.registerReceiver(this.mBatInfoReceiver, 
				new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        list = (ListView)this.findViewById(R.id.resourcelist);
		list.setItemsCanFocus(false);
		list.setChoiceMode(ListView.PERSISTENT_ANIMATION_CACHE);
		list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        populateSOSBtn();
        populateWifiBtn();
        //populateMapButton();
        populateHotspotButton();
        populateList();
        
        hotSpot =(ToggleButton) findViewById(R.id.hotspotButton);
        if(isNetworkAvailable()){
        	
        	hotSpot.setVisibility(BIND_AUTO_CREATE);
        	hotSpot.setChecked(true);
        	hotspotDialog();
			
        }
        else{
        	hotSpot.setVisibility(BIND_NOT_FOREGROUND);
        	AlertDialog rD = MainPage.this.wifiDialog();
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
	                   WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			
			rD.show();
        }
		
    }
    private void populateList() {
    	final ArrayList<ResourceView> image_details = GetSearchResults();
    	 
    	 list.setAdapter(new ResourceViewAdaptor(this, image_details));
    	 list.setOnItemClickListener(new OnItemClickListener() {
    	 public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {

    		 Intent mainIntent = new Intent(MainPage.this, MyMap.class);
    		 mainIntent.putExtra("param", position);
				MainPage.this. startActivityForResult(mainIntent,GET_CODE);
				overridePendingTransition(R.anim.fade, R.anim.hold);
				
			}
    	 });
    }
	private void populateHotspotButton() {
		
		hotSpot =(ToggleButton) findViewById(R.id.hotspotButton);
    	hotSpot.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				hotspotDialog();
				
			}

			
		
	});
	}
	private void hotspotDialog() {
		final Dialog dlg1 = new Dialog(MainPage.this);
    	LayoutInflater li = (LayoutInflater) MainPage.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (hotSpot.isChecked()){
		View v1 = li.inflate(R.layout.hotspot_message, null, false);
		dlg1.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dlg1.setContentView(v1);
		
		dlg1.show();
		batteyLevel = (TextView) dlg1.findViewById(R.id.battery_status);
		batteyLevel.setText(String.valueOf(level) + "%");
		yesBtn = (Button) dlg1.findViewById(R.id.yesbutton);
        
        yesBtn.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			hotSpot.setChecked(true);
    			WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    			Method[] wmMethods = wifi.getClass().getDeclaredMethods();
    			for(Method method: wmMethods){
    			  if(method.getName().equals("setWifiApEnabled")){
    			    netConfig = new WifiConfiguration();
    			    netConfig.SSID = "\"Emergency Hotspot\"";
    			    netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    			    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    			    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    			    netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);    netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    			    netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    			    netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    			    netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);  
    			   
    			    try {
    			      method.invoke(wifi, netConfig,true);
    			    } catch (IllegalArgumentException e) {
    			      e.printStackTrace();
    			    } catch (IllegalAccessException e) {
    			      e.printStackTrace();
    			    } catch (InvocationTargetException e) {
    			      e.printStackTrace();
    			    }
    			  }
    			}
    			dlg1.dismiss();	
    		}
		});
        noBtn = (Button) dlg1.findViewById(R.id.nobutton);
        noBtn.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			hotSpot.setChecked(false);
    			
    			dlg1.dismiss();	
    			
    		}
		});
    	
		
		
		
		
		}
		else{
			View v1 = li.inflate(R.layout.hotspot_message_off, null, false);
			dlg1.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dlg1.setContentView(v1);
			dlg1.show();
			yesBtn = (Button) dlg1.findViewById(R.id.yesbutton);
	        
	        yesBtn.setOnClickListener(new View.OnClickListener() {
	    		public void onClick(View v) {
	    			hotSpot.setChecked(false);
	    			WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
	    			Method[] wmMethods = wifi.getClass().getDeclaredMethods();
	    			for(Method method: wmMethods){
	    			  if(method.getName().equals("setWifiApEnabled")){
	    			   
	    			   
	    			   
	    			    try {
	    			      method.invoke(wifi, netConfig,false);
	    			    } catch (IllegalArgumentException e) {
	    			      e.printStackTrace();
	    			    } catch (IllegalAccessException e) {
	    			      e.printStackTrace();
	    			    } catch (InvocationTargetException e) {
	    			      e.printStackTrace();
	    			    }
	    			  }
	    			}
	    			dlg1.dismiss();	
	    		}
			});
	        noBtn = (Button) dlg1.findViewById(R.id.nobutton);
	        noBtn.setOnClickListener(new View.OnClickListener() {
	    		public void onClick(View v) {
	    			hotSpot.setChecked(true);
	    			dlg1.dismiss();	
	    		}
			});
	    	
			
			
	}
	
		
	}
    protected AlertDialog wifiDialog() {
    	hotSpot =(ToggleButton) findViewById(R.id.hotspotButton);
		AlertDialog.Builder builder = new AlertDialog.Builder(MainPage.this);
		builder.setMessage("There is no internet conection\n. would you like to search for any availble network or try later?")
		.setCancelable(false)
		.setPositiveButton("Search", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				hotSpot.setChecked(false);
				Intent mainIntent = new Intent(MainPage.this, WifiList.class);
				MainPage.this. startActivityForResult(mainIntent,GET_CODE);
				overridePendingTransition(R.anim.fade, R.anim.hold);
				
			}
		})
		.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				finish();
			}
		});
		AlertDialog alert = builder.create();
		return alert;
	}

	
	
	private void populateWifiBtn() {
    	wifiButton =(ImageButton) findViewById(R.id.wifiButton);
    	wifiButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
			
		Intent mainIntent = new Intent(MainPage.this, WifiList.class);
		MainPage.this. startActivityForResult(mainIntent,GET_CODE);
		overridePendingTransition(R.anim.fade, R.anim.hold);
		
			}
		});
		
	}
	private void populateSOSBtn() {
		sos =(ImageButton) findViewById(R.id.buttonsos);
		Animation ranim = (Animation)AnimationUtils.loadAnimation(MainPage.this, R.anim.fade_in);
		sos.setAnimation(ranim);
		sos.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
			
		Intent mainIntent = new Intent(MainPage.this, SOS.class);
		MainPage.this. startActivityForResult(mainIntent,GET_CODE);
		overridePendingTransition(R.anim.zoom_enter, R.anim.hold);
		
			}
		});
	}
	private ArrayList<ResourceView> GetSearchResults(){
		ArrayList<ResourceView> results = new ArrayList<ResourceView>();

		ResourceView item_details = new ResourceView();
		item_details.setName("Hospital");
		item_details.setImageNumber(1);
		results.add(item_details);

		item_details = new ResourceView();
		item_details.setName("Pharmacy");
		item_details.setImageNumber(2);
		results.add(item_details);

		item_details = new ResourceView();
		item_details.setName("Stores");
		item_details.setImageNumber(3);
		results.add(item_details);

		item_details = new ResourceView();
		item_details.setName("Gas Station");
		item_details.setImageNumber(4);
		results.add(item_details);

		

		


		return results;
		}
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
	@Override
    public void onResume() {
		 super.onResume();
		hotSpot =(ToggleButton) findViewById(R.id.hotspotButton);
		if(isNetworkAvailable()){
        	
        	hotSpot.setVisibility(BIND_AUTO_CREATE);
        	
			
        }
        else{
        	hotSpot.setVisibility(BIND_NOT_FOREGROUND);
        	AlertDialog rD = MainPage.this.wifiDialog();
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
	                   WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			
			rD.show();
        }
	}
	@Override
    public void onDestroy() {
		 super.onDestroy();
	this.unregisterReceiver(this.mBatInfoReceiver);
	}
	private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context arg0, Intent intent) {
		
		level = intent.getIntExtra("level", 0);
			}
       };
       
}